# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
import time
import random
import telnetlib
from selenium import webdriver
from scrapy.conf import settings
from scrapy.http import HtmlResponse
from selenium.webdriver.common.action_chains import ActionChains


class ProxyMiddleware(object):
    def process_request(self, request, spider):
        if spider.name == 'XiciProxy':
            print('ProxyMiddleware XiciProxySpider')
        elif spider.name == 'JiguangProxy':
            print('ProxyMiddleware JiguangProxySpider')
        else:
            if spider.proxy_list:
                print('ProxyMiddleware spider.proxy_list')
                proxy_list = spider.proxy_list
            else:
                print('ProxyMiddleware IP_POOL')
                proxy_list = settings['IP_POOL']
            proxy = random.choice(proxy_list)
            result = proxy.split(':')
            try:
                telnetlib.Telnet(result[1][2:], port=result[2], timeout=2)  # 验证是否可用
            except:
                print('Proxy valid failed:' + proxy)
                return request
            else:
                print('Proxy valid success:' + proxy)
                request.meta['proxy'] = proxy


class UAMiddleware(object):
    def process_request(self, request, spider):
        ua = random.choice(settings['USER_AGENT_LIST'])
        request.headers['User-Agent'] = ua
        request.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
        request.headers['Accept-Encoding'] = 'gzip, deflate, br'
        request.headers['Accept-Language'] = 'zh-CN,zh;q=0.9'
        request.headers['Connection'] = 'keep-alive'
        request.headers['Upgrade-Insecure-Requests'] = '1'
        if spider.name == 'meituan':
            referer = random.choice(settings['MEITUAN_REFERER'])
            request.headers['Host'] = 'wh.meituan.com:443'
            request.headers['Referer'] = referer
        elif spider.name == 'tianmao':
            referer = random.choice(settings['TIANMAO_REFERER'])
            request.headers['Host'] = 'list.tmall.com:443'
            request.headers['Referer'] = referer
        elif spider.name == 'XiciProxy':
            request.headers['Host'] = 'www.xicidaili.com:443'
            request.headers['Referer'] = 'https://www.xicidaili.com/'


class SeleniumMiddleware(object):
    cookies = '__mta=45446811.1552404704175.1552404704175.1552404781225.2; uuid=8b700dca2a9c4d3ab8cf.1552404626.1.0.0; _lxsdk_cuid=16972873a2fc8-08c4a0f9917284-3d644601-100200-16972873a30c8; ci=57; rvct=57; _lxsdk_s=16972873a32-627-432-564%7C%7C5'
    isLoad = False

    def process_request(self, request, spider):
        print('SeleniumMiddleware process_request')
        if spider.name == 'meituan':
            options = webdriver.ChromeOptions()

            options.add_argument('--window-size=1366,768')
            # options.add_argument('--user-agent=' + str(request.headers['User-Agent'], encoding = "utf8"))
            # options.add_argument('--proxy-server=' + request.meta['proxy'])
            # options.add_argument('--cookie=' + self.cookies)
            driver = webdriver.Chrome(chrome_options=options)
            driver.set_page_load_timeout(10)
            # for item in cookies.split(';'):
            #     name, value = item.split('=', 1)
            #     cookie = {}
            #     cookie['name'] = name
            #     cookie['value'] = value
            #     print(cookie)
            #     driver.add_cookie(cookie)
            # source = []
            response = ''
            for i in range(1, 7):
                try:
                    if not self.isLoad:
                        driver.get(request.url)
                        driver.implicitly_wait(10)
                        self.isLoad = True
                    time.sleep(5)
                    btn_array = driver.find_elements_by_xpath('//p[@class="toggle-btn"]')
                    for btn in btn_array:
                        ActionChains(driver).move_to_element(btn).click(btn).perform()
                    print('toggle_btn')
                    response += driver.page_source
                    time.sleep(5)
                    pagination_next = driver.find_element_by_xpath('//a[@class="pagination-item next-btn active"]')
                    ActionChains(driver).move_to_element(pagination_next).click(pagination_next).perform()
                    time.sleep(5)
                except Exception as e:
                    print(e)
                    driver.close()
                    # return request
                # else:
                #     # source.append(driver.page_source)
            return HtmlResponse(request.url, body=response, encoding='utf-8', request=request)
        elif spider.name == 'tianmao':
            driver = webdriver.Chrome()
            driver.set_page_load_timeout(10)
            response = ''
            for i in range(1, 3):
                try:
                    if not self.isLoad:
                        driver.get(request.url)
                        driver.implicitly_wait(10)
                        self.isLoad = True
                    response += driver.page_source
                    time.sleep(5)
                    pagination_next = driver.find_element_by_xpath('//a[@class="ui-page-next"]')
                    ActionChains(driver).move_to_element(pagination_next).click(pagination_next).perform()
                    time.sleep(5)
                except Exception as e:
                    print(e)
                    driver.close()
                    # return request
                # else:
                #     # source.append(driver.page_source)
            return HtmlResponse(request.url, body=response, encoding='utf-8', request=request)


class MyscrapySpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class MyscrapyDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        # request.find_element_by_xpath('//div[@class="list-item-desc"]')
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
